package cn.edu.sdjzu.xg.kcsj.filter;

import cn.edu.sdjzu.xg.kcsj.exception.BysjException;
import cn.edu.sdjzu.xg.kcsj.util.JwtUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "F01_JwtFilter", urlPatterns = {"/*"})
public class JwtFilter implements Filter {
    // 记录器，可以控制日志信息输出到控制台，替代输出语句
    private static final Logger log = LogManager.getLogger(JwtFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse) resp;
        // 请求URL
        String requestURL = request.getRequestURL().toString();
        // 如果是登录请求，直接放行
        if(requestURL.contains("login.ctl")){
            log.debug("REQ = "+ requestURL);
            chain.doFilter(req, resp);
            return;
        }
        // 创建JSON对象message，以便往前端响应信息
        JSONObject message_jsonObj = new JSONObject();
        try {
            // 解析token
            JwtUtil.verifyToken(request);
            log.debug("valid");
            chain.doFilter(req, resp);
        } catch (BysjException e) { // 各种情况都写在了JwtUtil里
            e.printStackTrace();
            message_jsonObj.put("message", e.getMessage());
            response.getWriter().println(message_jsonObj);
        } catch (Exception e) {
            e.printStackTrace();
            message_jsonObj.put("message", e.getMessage());
            response.getWriter().println(message_jsonObj);
        }
    }
}
